package com.webserver_v5.core;
import com.webserver_v5.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;

    private static File rootDir;
    private static File staticDir;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    static {
        try {
            rootDir = new File(
                    ClientHandler.class.getClassLoader()
                    .getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
            //1.接收请求
            HttpServletRequest request = new HttpServletRequest(socket);
            //2.处理请求
            String path = request.getUri();

            //3.发送响应
            File file = new File(staticDir,path);
            int statusCode;
            String statusReason;
            if (file.isFile()){
                statusCode = 200;
                statusReason = "OK";
            }else {
                statusCode = 404;
                statusReason = "NotFound";
                file = new File(staticDir,"root/404.html");
            }
            //(3.1).发送响状态
            println("HTTP/1.1 200 OK");
            //(3.2).发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            //(3.3).单独发送回车和换行表示响应头发送完毕
            println("");
            //(3.4).发送响应正文
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] data = new byte[10240];
            int len;
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }
}
